package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


@RestController
@Slf4j
public class RadarController {

    
   /*
     * @Description //雷达请求接口  接口path="/AeroSense" POST请求
     * @Param * @param: request
     * @return java.lang.String 
     **/
    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/AeroSense", method = RequestMethod.POST)
    public String AeroSense(HttpServletRequest request) {
        /*字节流接收雷达数据*/
        InputStream inputStream = null;
        try {
            //获取雷达请求的数据
            inputStream = request.getInputStream();
            //创建缓冲输入流
            BufferedInputStream byteOutputStream = new BufferedInputStream(inputStream);
            //创建输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //创建字节数组
            byte[] bytes = new byte[1024];
            int a;
            //读取输入流数据到输出流
            while ((a = byteOutputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, a);
            }
            //将输出流数据转为String格式为utf-8
            String s = byteArrayOutputStream.toString("utf-8");
            /*分析雷达数据*/
            String[] Map = s.split(",");
            /*判断类型*/
            switch (Map[0]) {
                case "KeepAlive"://雷达联网检测
                    log.info("收到雷达联网请求,雷达ID为：《" + Map[1] + "》硬件版本号为:" + Map[2]);
                    break;
                case "FallDetect"://雷达电话报警
                    log.info("收到报警，雷达ID为：《" + Map[1] + "》===硬件版本号为:" + Map[2]);
                    break;
                case "HeatMap": //热力图
                    log.info("收到热力图上传请求，雷达Id为：《" + Map[1] + "》=====状态：" + Map[2]);
                    break;
                default:
                    return "OK";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //保证最终响应 Ok
            return "OK";
        }
    }
}
